package com.twu.biblioteca.model;

import com.google.inject.Inject;

import com.twu.biblioteca.dao.MovieDao;
import com.twu.biblioteca.entity.Movie;
import com.twu.biblioteca.exception.CheckoutFailException;
import com.twu.biblioteca.exception.ReturnFailException;

import java.util.List;


public class MovieModel {
  private final MovieDao dao;

  @Inject
  public MovieModel(MovieDao dao) {
    this.dao = dao;
  }

  public List<Movie> checkout(Movie movie) {
    List<Movie> allAvailableMovies = dao.getAvailableMovies();
    if (!allAvailableMovies.contains(movie)) {
      throw new CheckoutFailException("Movie is not existing or already checked out");
    }

    for (Movie m : allAvailableMovies) {
      if (m.getEidr().equals(movie.getEidr())) {
        m.setAvailable(false);
        dao.update(m.getUuid(), m);
        break;
      }
    }

    return dao.getAvailableMovies();
  }

  public List<Movie> returnMovie(Movie movie) {
    List<Movie> checkoutMovies = dao.getCheckoutMovies();
    if (!checkoutMovies.contains(movie)) {
      throw new ReturnFailException("Request is not valid, check movie again");
    }

    for (Movie m : checkoutMovies) {
      if (m.getEidr().equals(movie.getEidr())) {
        m.setAvailable(true);
        dao.update(m.getUuid(), m);
        break;
      }
    }

    return dao.getAvailableMovies();
  }

  public List<Movie> getAvailableMovies() {
    return dao.getAvailableMovies();
  }

  public List<Movie> getCheckoutMovies() {
    return dao.getCheckoutMovies();
  }
}
